package com.lgy.controller;

import com.lgy.dto.OrderDTO;
import com.lgy.enums.ResultEnum;
import com.lgy.exception.SellException;
import com.lgy.form.OrderForm;
import com.lgy.service.BuyerService;
import com.lgy.service.OrderService;
import com.lgy.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.lgy.converter.OrderFormToOrderDTOConverter.convert;

@RestController
@RequestMapping("buyer/order")
public class BuyerOrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private BuyerService buyerService;

    // 创建订单
    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm) throws SellException {
        OrderDTO orderDTO = convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderDTO createResult = orderService.create(orderDTO);
        Map<String, String> map = new HashMap();
        map.put("orderId", createResult.getOrderId());
        return success(null, map);
    }

    // 订单列表
    @GetMapping("/list")
    public ResultVO list(@RequestParam("openid") String openid,@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
                         @RequestParam(value = "size", defaultValue = "10", required = false) Integer size ) throws SellException {
        if(StringUtils.isEmpty(openid)) {
            throw new SellException("openid不能为空");
        }

        PageRequest request = PageRequest.of(page, size);
        Page<OrderDTO> orderDTOPage = orderService.findList(openid, request);
        return success(null, orderDTOPage);
    }

    // 订单详情
    @GetMapping("/detail")
    public ResultVO detail(@RequestParam("openid") String openid,@RequestParam("orderId") String orderId) throws SellException {
        if(StringUtils.isEmpty(openid)) {
            throw new SellException("openid不能为空");
        }

        if(StringUtils.isEmpty(orderId)) {
            throw new SellException("orderId不能为空");
        }

        return success(null, buyerService.findOrderOne(openid, orderId));
    }


    // 取消订单
    @PostMapping("/cancel")
    public ResultVO create(@RequestParam("openid") String openid,@RequestParam("orderId") String orderId) throws SellException {
        if(StringUtils.isEmpty(openid)) {
            throw new SellException("openid不能为空");
        }

        if(StringUtils.isEmpty(orderId)) {
            throw new SellException("orderId不能为空");
        }

        return success();
    }

}
